로딩 중이에요... 🐣
[코담]
웹개발·실전 프로젝트·AI까지, 파이썬·장고의 모든것을 담아낸 강의와 개발 노트
09 폼(Form) 처리하기 | ✅ 편저: 코담 운영자
Django 튜토리얼 #9 - 폼(Form) 처리하기
🔗 소스
1. 강의 목표
- Django의
forms
기능을 이용하여 사용자 입력을 받고 처리하는 방법을 학습한다. - HTML 폼 구조, Django 폼 클래스 정의, 검증 및 전송 흐름을 실습한다.
2. Django Forms의 장점
- 자동 검증 기능 제공 (
is_valid()
활용) - CSRF 방지 토큰 자동 적용 (
{% csrf_token %}
) - 재사용성 높은 폼 클래스 생성 가능
- 에러 메시지 및 필드 위젯 등 커스터마이징 용이
3. 폼 클래스 정의 (forms.py)
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
def send_email(self):
print(f"Sending email from {self.cleaned_data['email']} with message {self.cleaned_data['message']}")
forms.Form
상속 → 일반적인 폼 생성cleaned_data
→ 유효성 검사를 통과한 사용자 입력 값 딕셔너리
4. 뷰 함수 정의 (views.py)
from django.shortcuts import render, redirect
from .forms import ContactForm
# 홈 화면
def home_view(request):
return render(request, 'formoreapp/home.html')
# 폼 입력 화면
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.send_email()
return redirect('contact_success')
else:
form = ContactForm()
return render(request, 'formoreapp/contact.html', {'form': form})
# 제출 완료 화면
def contact_success_view(request):
return render(request, 'formoreapp/contact_success.html')
5. URL 연결 (urls.py)
from django.urls import path
from . import views
urlpatterns = [
path('', views.home_view, name='home'),
path('contact/', views.contact_view, name='contact'),
path('contact/success/', views.contact_success_view, name='contact_success')
]
6. 디렉토리 및 템플릿 구조
lesson9-DjangoForms/
├── form_project/
│ ├── form_app/
│ │ ├── migrations/
│ │ ├── templates/
│ │ │ └── form_app/
│ │ │ ├── contact.html
│ │ │ ├── contact_success.html
│ │ │ └── home.html
│ │ ├── admin.py
│ │ ├── apps.py
│ │ ├── form.py
│ │ ├── models.py
│ │ ├── tests.py
│ │ ├── urls.py
│ │ └── views.py
│ ├── form_project/
│ │ ├── __init__.py
│ │ ├── asgi.py
│ │ ├── settings.py
│ │ ├── urls.py
│ │ └── wsgi.py
│ ├── db.sqlite3
│ ├── manage.py
│ └── Pipfile
form_app
하위에templates/form_app/
폴더 생성- 각각
home.html
,contact.html
,contact_success.html
템플릿이 위치
home.html
{% load static %}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>홈</title>
<link rel="stylesheet" href="{% static 'styles/styles.css' %}">
</head>
<body>
<div class="centered-content">
<img src="{% static 'images/logo.png' %}" alt="로고">
<form action="{% url 'contact' %}" method="get">
<button type="submit" class="btn">폼으로 이동</button>
</form>
</div>
</body>
</html>
contact.html
{% load static %}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
<link rel="stylesheet" href="{% static 'styles/styles.css' %}">
</head>
<body>
<h1>Contact Us</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">제출</button>
</form>
</body>
</html>
contact_success.html
{% load static %}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>성공</title>
<link rel="stylesheet" href="{% static 'styles/styles.css' %}">
</head>
<body>
<h1>성공적으로 전송되었습니다</h1>
<p>빠른 시일 내에 연락드리겠습니다.</p>
<a href="{% url 'home' %}">홈으로 돌아가기</a>
</body>
</html>
- 템플릿 파일은 앱 내부의
templates/form_app/
구조로 관리됨 - 정적 리소스는
{% static %}
태그를 사용해 연결
7. 실습 요약
- 폼 클래스 정의 및 HTML 렌더링 완료
- 사용자 입력값 POST 전송 및 검증 처리
- 유효 시
send_email()
실행 후 성공 페이지로 리디렉션
다음 강의 예고
- Django 사용자 인증(Authentication) 시스템 도입 및 로그인/회원가입 처리